#include "ConfigAnaly.h"
#include <stdlib.h>
#include <ctype.h>
#include <stdio.h>

void ConfigAnaly::alayze_config(const char *config_name)
{
	if(config_name == NULL)
	{
		printf("the config name not allow equal to null");
		exit(1);
	}

	char buff[400], line[400];
    int start = 0, end = 0, index = 0;
    bool track = false;
    int number = 0;

	FILE *fp = fopen(config_name, "r");
    if(fp == NULL)
    {
        printf("read config file %s error\n", config_name);
        abort();
    }

    while(!feof(fp))
    {
        buff[0] = '\0';
        start = end = index = 0;
        track = false;
        number++;

        fgets(buff, sizeof(buff), fp);

        //clear str left space
        while(buff[start] != '\0' && isspace(buff[start]))
        {
            start++;
        }

        //clear str symbol '#' right data
        end = start;
        while(buff[end] != '\0' && buff[end] != '#')
        {
            end++;
        }

        if(end - start == 0)
        {
            continue;
        }

        //clear str right space
        for(int i = start; i < end; i++)
        {
            if(isspace(buff[i]))
            {
                if(!track)
                {
                    track = true;
                    index = i;
                }
            }else{
                track = false;
            }
        }

        if(track)
        {
            end = index;
        }

        //copy str to line
        index = 0;
        for(int i = start; i < end; i++)
        {
            line[index++] = buff[i];
        }
        line[index] = '\0';

        analyze_config_line(line, number);
    }

}

void ConfigAnaly::analyze_config_line(char *line, int number)
{
    if(line == NULL)
        return;

    unsigned int index = 0, i = 0;
    char config_name[200];
    char config_value[200];

    while(line[index] != '\0' && !isspace(line[index]))
    {
        config_name[i++] = line[index++];
        if(i >= sizeof(config_name) - 1)
        {
            goto FAILD;
        }
    }
    config_name[i] = '\0';

    //not exists config_value data, we goto faild
    if(line[index] == '\0')
    {
        goto FAILD;
    }

    //skip space char
    while(line[index] != '\0' && isspace(line[index]))
    {
        index++;
    }

    i = 0;
    while(line[index] != '\0' && !isspace(line[index]))
    {
        config_value[i++] = line[index++];
        if(i >= sizeof(config_value) -1)
        {
            goto FAILD;
        }
    }

    //unnecessary data, goto faild
    if(line[index] != '\0')
    {
        goto FAILD;
    }

	config_map.insert(std::make_pair(config_name, config_value));

    return;

FAILD:
    printf("the config line number %d format error!\n", number);
    exit(1);
}

std::string ConfigAnaly::getConfigByName(std::string config_name)
{
	return config_map[config_name];
}
